<template>
  <div class="list">
    <van-dropdown-menu>
      <van-dropdown-item v-model="objs.orderBy" :options="option1" />
    </van-dropdown-menu>
  </div>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <Carll v-for="item in list" :key="item.id" :item />
    </van-list>
  </van-pull-refresh>
</template>

<script lang="ts" setup>
import Carll from './Carll.vue'
import { getCourseList } from '@/services/user'
import { ref, watch } from 'vue'
const list: any = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const props = defineProps<{
  active: any

  searchValue: any
}>()
const option1 = [
  { text: '全部课程', value: 0 },
  { text: '时间排序', value: 1 },
  { text: '热度排序', value: 2 }
]
const objs = ref({
  pageNum: 1,
  pageSize: 10,
  catId: '',
  orderBy: 0,
  searchValue: ''
})
// 监听 searchValue 的变化
watch(
  () => props.searchValue,
  (newValue, oldValue) => {
    objs.value.searchValue = newValue
    onSearchc()
  }
)

// 搜索功能
const onSearchc = async () => {
  objs.value.pageNum = 1 // 重置页码
  list.value = [] // 清空当前列表
  finished.value = false // 重置加载完成状态
  loading.value = true // 开始加载
  await onLoad() // 调用加载函数执行搜索
}

// 加载列表数据
const onLoad = async () => {
  try {
    objs.value.catId = props.active == 0 ? '' : props.active
    const res = await getCourseList(objs.value)
    list.value.push(...res.rows)
    //total这个是总条数
    if (objs.value.pageNum >= Math.ceil(res.total / objs.value.pageSize)) {
      finished.value = true
    } else {
      objs.value.pageNum++
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 重新刷新列表
const onRefresh = () => {
  objs.value.catId = props.active == 0 ? '' : props.active
  finished.value = false
  objs.value.pageNum = 1
  list.value = []
  loading.value = true
  onLoad()
}
</script>

<style lang="scss" scoped>
.list {
  width: 100%;
  height: 30px;
}
:deep() .van-dropdown-menu__bar {
  height: 30px;
}
:deep().van-dropdown-menu__item {
  width: 86px;
  flex: none;
}
:deep() .van-ellipsis {
  font-size: 13px;
}
.van-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding-bottom: 40px;
}

:deep() .van-list__finished-text {
  width: 100%;
  text-align: center;
}
</style>
